package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.mapper.AuthorMapper;
import com.heima.article.service.GeneratePageService;
import com.heima.common.exception.CustException;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.enums.AppHttpCodeEnum;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.json.Json;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class GeneratePageServiceImpl implements GeneratePageService {
    @Autowired
    private Configuration configuration;
    @Autowired
    private AuthorMapper authorMapper;
    @Resource(name = "minIOFileStorageService")
    private FileStorageService fileStorageService;
    @Autowired
    ApArticleMapper apArticleMapper;
    @Value("${file.minio.prefix}")
    private String prefix;
    @Value("${file.minio.readPath}")
    String readPath;

    /**
     * 生成静态页面的方法
     *
     * @param content
     * @param apArticle
     */
    @Override
    public void generateArticlePage(String content, ApArticle apArticle)    {
        //1.先获取模板对象article.ftl
        try {
            Template template = configuration.getTemplate("article.ftl");
            Map params = new HashMap<>();
            ApAuthor apAuthor = authorMapper.selectById(apArticle.getAuthorId());
            params.put("authorApUserId",apAuthor.getUserId());
            params.put("article",apArticle);
            params.put("content", JSON.parseArray(content,Map.class));
            StringWriter writer = new StringWriter();
            template.process(params,writer);
            ByteArrayInputStream inputStream = new ByteArrayInputStream(writer.toString().getBytes());
            String store = fileStorageService.store(prefix, apArticle.getId() + ".html", "text/html", inputStream);
            apArticle.setStaticUrl(store);
            apArticleMapper.updateById(apArticle);
            log.info("成功生成文章静态页面===>地址:{}",readPath+store);
        } catch (Exception e) {
            e.printStackTrace();
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR, "生成静态页失败");
            log.error("生成文章失败==>原因: {}",e.getMessage());
        }
    }
}